package com.daoliuhe.scaffold.tools;


import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MailUtil {

    /**
     * 通知管理员
     *
     * @param subject
     * @param content
     * @throws MessagingException
     */
    public static void notifyAdmin(String subject, String content) {
        if (null != Config.MAIL_ADMIN_MAILS && !Config.MAIL_ADMIN_MAILS.isEmpty()) {
            sendMail(Config.MAIL_ADMIN_MAILS, null, subject, content);
        }
    }

    /**
     * 发送邮件
     *
     * @param toEmail_TO 主送
     * @param toEmail_CC 抄送
     * @param subject
     * @param text
     * @throws MessagingException
     */
    public static boolean sendMail(String toEmail_TO, String toEmail_CC, String subject,
                                   String text, Boolean... html) {
        final String username = Config.MAIL_USERNAME; // 发件人的邮件帐户
        final String password = Config.MAIL_PASSWORD; // 发件人的邮件密码
        boolean ret = true;
        try {
            // 创建Properties 对象
            Properties props = System.getProperties();

            // 添加smtp服务器属性
            props.put("mail.smtp.host", Config.MAIL_SMTP_SERVER);
            props.put("mail.smtp.auth", "true"); // 163的smtp不是免费的也不公用的，需要验证

            // 创建邮件会话
            Session session = Session.getInstance(props, new Authenticator() { // 验账账户
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });

            String args_to[] = toEmail_TO.split(",");

            InternetAddress[] adds_to = new InternetAddress[args_to.length];
            for (int i = 0; i < args_to.length; i++) {
                adds_to[i] = new InternetAddress(args_to[i].trim());
            }

            toEmail_CC = toEmail_CC == null ? "" : toEmail_CC;
            String args_cc[] = toEmail_CC.split(",");
            if ("".equals(toEmail_CC)) {
                args_cc = new String[0];
            }

            InternetAddress[] adds_cc = new InternetAddress[args_cc.length];
            for (int i = 0; i < args_cc.length; i++) {
                adds_cc[i] = new InternetAddress(args_cc[i].trim());
            }

            // 定义邮件信息
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(Config.MAIL_FROM_EMAIL));
            message.addRecipients(Message.RecipientType.TO, adds_to);

            // 抄送人员不存在则不抄送
            if (null != adds_cc && adds_cc.length > 0) {
                message.addRecipients(Message.RecipientType.CC, adds_cc);
            }

            message.setSubject(subject);
            if (html != null && html.length == 1 && html[0] == true) {
                message.setContent(text, "text/html;charset=gb2312");
            } else {
                message.setText(text);
            }

            // 发送消息
            // session.getTransport("smtp").send(message); //也可以这样创建Transport对象
            Transport.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            ret = false;
        }

        return ret;
    }

    /**
     * 是否是合法邮箱地址
     *
     * @param str
     * @return
     */
    public static boolean isMailAddress(String str) {
        boolean result = false;
        if (null == str || str.isEmpty()) {

        } else {
            Pattern pattern = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
            Matcher matcher = pattern.matcher(str);
            result = matcher.matches();
        }
        return result;
    }

}
